package com.wg.core.thread.fiber;

import java.util.concurrent.RejectedExecutionException;

/**
 * 任务拒绝策略接口，处理队列满时的任务
 */
@FunctionalInterface
public interface RejectedTaskHandler {

    /**
     * 处理被拒绝的任务
     * @param task 被拒绝的任务
     * @param fiber 当前 PoolFiber 实例
     * @throws RejectedExecutionException 可选择抛出异常
     */
    void rejected(Runnable task, PoolFiber fiber) throws RejectedExecutionException;

    /**
     * 静默丢弃任务（默认实现）
     */
    RejectedTaskHandler DISCARD = (task, fiber) -> {
        // 可添加日志记录
    };

    /**
     * 阻塞等待队列有空间（最多等待1秒）
     */
    RejectedTaskHandler BLOCKING = (task, fiber) -> {
        try {
            boolean added = fiber.tryOfferTaskWithTimeout(task, 1, java.util.concurrent.TimeUnit.SECONDS);
            if (!added) {
                throw new RejectedExecutionException("Task rejected after 1s wait, queue full. Capacity: " + fiber.getQueueCapacity());
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RejectedExecutionException("Interrupted while waiting for queue space", e);
        }
    };

    /**
     * 重试3次后丢弃
     */
    RejectedTaskHandler RETRY_3_TIMES = (task, fiber) -> {
        int retryCount = 3;
        for (int i = 0; i < retryCount; i++) {
            try {
                if (fiber.tryOfferTask(task)) {
                    return; // 重试成功
                }
                Thread.sleep(100); // 间隔100ms重试
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RejectedExecutionException("Interrupted during retry", e);
            }
        }
        throw new RejectedExecutionException("Task rejected after 3 retries, queue full. Capacity: " + fiber.getQueueCapacity());
    };
}
